package com.reservation.controller;

import com.reservation.entity.Reservation;
import com.reservation.service.ReservationService;
import com.reservation.utils.ResponseResult;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping(value = "/api/reservation")
public class ReservationController {

    private static final Logger log = LoggerFactory.getLogger(ReservationController.class);

    @Autowired
    private ReservationService reservationService;

    @Value("${server.port}")
    private int serverPort;

    /**
     * 添加预订信息
     */
    @PostMapping("/add.do")
    @CircuitBreaker(name = "reservationService", fallbackMethod = "fallbackAddReservation")
    public ResponseResult addReservation(@RequestBody Reservation reservation) {
        if (reservationService.insertReservation(reservation)) {
            return ResponseResult.success("添加预订成功！");
        } else {
            return ResponseResult.failure("添加预订失败！");
        }
    }

    public ResponseResult fallbackAddReservation(@RequestBody Reservation reservation, Throwable throwable) {
        System.err.println("断路器触发 - 添加预订失败: " + throwable.getMessage());
        return ResponseResult.failure("系统繁忙，请稍后再试");
    }

    /**
     * 修改预订信息
     */
    @PostMapping("/update.do")
    @CircuitBreaker(name = "reservationService", fallbackMethod = "fallbackUpdateReservation")
    public ResponseResult updateReservation(@RequestBody Reservation reservation) {
        if (reservationService.updateReservation(reservation)) {
            return ResponseResult.success("更新预订成功！");
        } else {
            return ResponseResult.failure("更新预订失败！");
        }
    }

    public ResponseResult fallbackUpdateReservation(@RequestBody Reservation reservation, Throwable throwable) {
        System.err.println("断路器触发 - 更新预订失败: " + throwable.getMessage());
        return ResponseResult.failure("系统繁忙，请稍后再试");
    }

    /**
     * 删除预订信息
     */
    @PostMapping("/delete.do")
    @CircuitBreaker(name = "reservationService", fallbackMethod = "fallbackDeleteReservation")
    public ResponseResult deleteReservation(@RequestParam Integer rid) {
        if (reservationService.deleteReservation(rid)) {
            return ResponseResult.success("删除预订成功！");
        } else {
            return ResponseResult.failure("删除预订失败！");
        }
    }

    public ResponseResult fallbackDeleteReservation(@RequestParam Integer rid, Throwable throwable) {
        System.err.println("断路器触发 - 删除预订失败: " + throwable.getMessage());
        return ResponseResult.failure("系统繁忙，请稍后再试");
    }

    /**
     * 获取单个预订信息
     */
    @GetMapping("/get.do")
    @CircuitBreaker(name = "reservationService", fallbackMethod = "fallbackGetReservation")
    public ResponseResult getReservation(@RequestParam Integer rid) {
        Reservation reservation = reservationService.getReservationById(rid);
        if (reservation != null) {
            return ResponseResult.success("获取预订成功！", reservation);
        } else {
            return ResponseResult.failure("获取预订失败！");
        }
    }

    public ResponseResult fallbackGetReservation(@RequestParam Integer rid, Throwable throwable) {
        System.err.println("断路器触发 - 获取预订失败: " + throwable.getMessage());
        Reservation defaultReservation = new Reservation();
        return ResponseResult.success("系统繁忙，返回临时数据", defaultReservation);
    }

    /**
     * 获取预订列表（带熔断保护）
     */
    @GetMapping("/list.do")
    @CircuitBreaker(
            name = "reservationService",
            fallbackMethod = "fallbackGetReservationList"
    )
    public ResponseResult getReservationList() {
        log.info("获取预订列表");
        try {
            List<Reservation> list = reservationService.getAllReservations();
            return ResponseResult.success("获取预订列表成功！", list);
        } catch (Exception e) {
            log.error("获取预订列表异常", e);
            throw e; // 抛出异常，触发熔断
        }
    }

    public ResponseResult fallbackGetReservationList(Throwable throwable) {
        log.warn("断路器触发 - 获取预订列表失败: {}", throwable.getMessage());
        return ResponseResult.failure("服务暂时不可用，请稍后再试");
    }

    /**
     * 查询预订列表
     */
    @GetMapping("/query.do")
    @CircuitBreaker(name = "reservationService", fallbackMethod = "fallbackQueryReservationList")
    public ResponseResult queryReservationList(@RequestBody Reservation reservation) {
        List<Reservation> list = reservationService.getAllReservations(); // 这里假设 getAllReservations 可用于查询，根据实际修改
        return ResponseResult.success("查询预订列表成功！", list);
    }

    public ResponseResult fallbackQueryReservationList(@RequestBody Reservation reservation, Throwable throwable) {
        System.err.println("断路器触发 - 查询预订列表失败: " + throwable.getMessage());
        return ResponseResult.success("系统繁忙，返回部分数据", Collections.emptyList());
    }

    // ========== 测试接口（可选） ==========
    @GetMapping("/test-circuit-breaker")
    public ResponseResult testCircuitBreaker() {
        log.info("测试熔断 - 端口: {}", serverPort);
        try {
            List<Reservation> list = reservationService.getAllReservations();
            return ResponseResult.build(true, "操作成功（端口：" + serverPort + "）", list);
        } catch (Exception e) {
            return ResponseResult.build(false, "服务暂时不可用（可能触发熔断）", null);
        }
    }
}